package com.liu.eduService.controller;


import com.liu.R;
import com.liu.eduService.client.VodClient;
import com.liu.eduService.entity.EduVideo;
import com.liu.eduService.service.EduVideoService;
import com.liu.serviceBase.exception.MyException;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author LSJ
 * @since 2022-01-07
 */
@RestController
@RequestMapping("/eduService/video")
@CrossOrigin
public class EduVideoController {

    @Autowired
    private EduVideoService service ;

    @Autowired
    private VodClient vodClient;

    @PostMapping("addVideo")
    public R addvideo(@RequestBody  EduVideo eduVideo){
        boolean save = service.save(eduVideo);
        return save?R.ok():R.error();
    }
    @PostMapping("updatevideo")
    public R updatevideo(@RequestBody  EduVideo eduVideo){
        boolean update = service.updateById(eduVideo);
        return update?R.ok():R.error();
    }
    @DeleteMapping("/deletevideo/{VideoId}")
    // TODO 之后 课程小节需要删除 视频
    public R deletevideo(@PathVariable  String VideoId){
        EduVideo eduVideo = service.getById(VideoId);
        //查询云端视频id
        String videoSourceId = eduVideo.getVideoSourceId();
        System.out.println(videoSourceId);

//        判断视频ID是否为空
            if (ObjectUtils.isEmpty(videoSourceId)){
                throw new MyException(20001,"videoSourceId为空！");
            }
/*
        视频id不为空：
       删除视频时，先获取到视频的id，之后删除小节；再删除视频

        先删数据库，这个就不用考虑分布式事务问题
 */
        boolean delete = service.removeById(VideoId);

        R r = vodClient.deleteVideo(videoSourceId);
        if (r.getCode()==20001){
            throw new MyException(20001,"单个视频，服务中断！；熔断器");
        }
        return delete?R.ok():R.error();
    }
    @GetMapping("getVideoById/{Id}")
    // 根据小节id查询
    public R getVideoById(@PathVariable String Id){
        EduVideo video = service.getById(Id);
        return R.ok().data("video",video);
    }

    @DeleteMapping("/deletevideoBycourseId/{courseId}")
    // TODO 之后 课程小节需要删除 多个视频
    public R deletevideoBycourseId(@PathVariable  String courseId){
        boolean delete = service.deletevideoBycourseId(courseId);
        return delete?R.ok():R.error();
    }
}

